[Go] 使用protobuf进行序列化和反序列化 您所在的位置:网站首页 protobuf序列化和反序列化 bytes类型 [Go] 使用protobuf进行序列化和反序列化

[Go] 使用protobuf进行序列化和反序列化

2024-04-11 22:36| 来源: 网络整理| 查看: 265

先定义消息类型

orders.proto

syntax = "proto2"; package message; message Orders { required int32 order_id=1; required string title=2; }

在GOPATH创建目录和编译这个消息类型输出到该目录,包名是message

mkdir $GOPATH/src/message;protoc --go_out $GOPATH/src/message orders.proto

编写go文件进行序列化和反序列化刚才生成的包里的类型结构体数据

package main import "message" import "github.com/golang/protobuf/proto" import "fmt" func main() { orders := &message.Orders{ OrderId: proto.Int32(1), Title: proto.String("第一个订单"), } //序列化成二进制数据 ordersBytes, _ := proto.Marshal(orders) //反序列化二进制数据 twoOrders := &message.Orders{} proto.Unmarshal(ordersBytes, twoOrders) fmt.Println(twoOrders.GetTitle()) fmt.Println(twoOrders.GetOrderId()) }


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有